//
//  HomeViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/10/29.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "HomeViewController.h"
#import "MCHomeSlideView.h"
#import "MCMainNavigationController.h"
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "SocketRocketUtility.h"
#import "HomeBaseModel.h"
#import "AppDelegate.h"
#import "KKWebViewController.h"
#import "LeverageTradeViewController.h"

#define HEIGHT_SDCycleScrollView G_SCREENWIDTH*0.5
@interface HomeViewController ()<SDCycleScrollViewDelegate,UIAlertViewDelegate>

@property(nonatomic, strong)SDCycleScrollView *cycleScrollView;

@property(nonatomic, strong)MCHomeSlideView *segmentedView;

@property (nonatomic,strong) NSString * updateURL;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    [self setProperty];
    [self createUI];
    
   

}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWebSocketdidReceiveMessageNote object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWebSocketDidOpenNote object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_cycleScrollView adjustWhenControllerViewWillAppera];
    
    [HUD showProgress:@"" inView:self.segmentedView];

    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidOpen) name:kWebSocketDidOpenNote object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];
    
    
    NSString * URL = CLIENTUPDATE_URL;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    __weak __typeof(self)wself = self;
    
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:@{@"type":@"ios",@"version":app_Version} SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:wself.segmentedView];
        NSDictionary * dic = responseObject;
        if ([dic[@"data"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary * dicc = dic[@"data"];
            if([[dicc allKeys] containsObject:@"is_update"]&&[[dicc allKeys] containsObject:@"update_url"]){
                NSString * is_update = [NSString stringWithFormat:@"%@",dicc[@"is_update"]];
                NSString * update_url= [NSString stringWithFormat:@"%@",dicc[@"update_url"]];
                if ([is_update integerValue]>0) {
                    if (update_url.length>0) {
                        if (![update_url containsString:@"http"]) {
                            update_url = [NSString stringWithFormat:@"https://%@",update_url];
                        }
                        wself.updateURL = update_url;
                        [wself openUpdate:update_url];
                    }
                }
            }
        }
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:wself.segmentedView];

    }];
    [self loadData];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) { //确认
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.updateURL]];
    }
    [self exitApp];
}

- (void)exitApp{
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:0.4f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    
    
}

//检测更新弹框
-(void)openUpdate:(NSString *)url{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发现新版本，请更新！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.delegate=self;
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
    
}

-(void)loadData{

    WS(weakSelf);
    NSString * URL = [NSString stringWithFormat:@"%@/ex/currency/tradepair",DEFAULTSEVERBASEURL];
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:@{} SuccessBlock:^(id  _Nonnull responseObject) {
        
        NSDictionary * dic = responseObject;
        if (dic) {
            NSDictionary * dicc = dic[@"data"];
            HomeBaseModel * model  = [HomeBaseModel sharedHomeBaseModel];
            model = [HomeBaseModel mj_objectWithKeyValues:dicc];
            
            SocketRocketUtility * SK =[SocketRocketUtility instance];
            if (SK.socketReadyState != 1) {
                [SK SRWebSocketOpenWithURLString:WEBSOCKET_API_1];
            }
            [weakSelf OpenWebScocket];
            
            NSLog(@"------%ld-----",(long)SK.socketReadyState);
        }
    } FailureBlock:^(id  _Nonnull error) {

        
    }];
    
}

-(void)OpenWebScocket{
    
    [self sendData];
    [self performSelector:@selector(sendData) withObject:nil afterDelay:5];

}

-(void)sendData{
    SocketRocketUtility * SK =[SocketRocketUtility instance];
    NSData *data= [NSJSONSerialization dataWithJSONObject:@{
                                                            @"cmd": @"sub",
                                                            @"args": @"all-tickers"
                                                            } options:NSJSONWritingPrettyPrinted error:nil];
    [SK sendData:data];
}


- (void)SRWebSocketDidOpen {
//    NSLog(@"开启成功");
    SocketRocketUtility * SK =[SocketRocketUtility instance];
    NSLog(@"------%ld-----",(long)SK.socketReadyState);
    
}

- (void)SRWebSocketDidReceiveMsg:(NSNotification *)note {
    //收到服务端发送过来的消息
//    NSString * message = note.object;
//    NSLog(@"-----收到服务端发送过来的消息--------%@",message);
    
    SocketRocketUtility * SK =[SocketRocketUtility instance];
    NSLog(@"------%ld-----",(long)SK.socketReadyState);
    
    
    [HUD dismissInView:self.segmentedView];
    [_segmentedView.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];

    [_segmentedView.home_USDTCell.tableView reloadData];
    [_segmentedView.home_BTCCell.tableView reloadData];
    [_segmentedView.home_ETHCell.tableView reloadData];
    
}

#pragma mark===========setProperty=============
-(void)setProperty{
    self.view.backgroundColor=RGB(231, 231, 231);
    [UIApplication sharedApplication].statusBarHidden = NO;
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
}

-(void)createUI{
    NSArray *imagesURLStrings = @[
                                  TUPIAN_URL_1,
                                  TUPIAN_URL_2
                                  ];
    
    // 网络加载 --- 创建带标题的图片轮播器
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0,  G_SCREENWIDTH, HEIGHT_SDCycleScrollView)  delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    _cycleScrollView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    [self.view addSubview:_cycleScrollView];
    
    //采用网络图片
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.cycleScrollView.imageURLStringsGroup = imagesURLStrings;
    });
    
    
    //使用block监听点击事件:
    _cycleScrollView.clickItemOperationBlock = ^(NSInteger index) {
        NSLog(@"%ld", (long)index);
    };
    
    //也可以用代理,我本人更喜欢用代理,因为block会很慢
    
    NSArray *array = [NSArray arrayWithObjects:@"USDT",@"BTC",@"ETH",nil];
    _segmentedView = [MCHomeSlideView segmentControlViewWithFrame:CGRectMake(0, HEIGHT_SDCycleScrollView, G_SCREENWIDTH, G_SCREENHEIGHT-kStatusBarAndNavigationBarHeight-HEIGHT_SDCycleScrollView)];
    
    _segmentedView.normalColor = RGB(102,102,102);
    _segmentedView.selectedColor = MC_THEME_COLOR;
    _segmentedView.SlideSelectedColor=MC_THEME_COLOR;
    
    _segmentedView.titleArray = array;
    _segmentedView.selectedTitleArray = array;
    //    _segmentedView.delegate=self;
    [self.view addSubview:_segmentedView];
    WS(wself);
    _segmentedView.block = ^(HomeBaseTabCellModel * _Nonnull model) {
        HomeBaseModel * Hmodel = [HomeBaseModel sharedHomeBaseModel];
        if (Hmodel.selectedModel) {
            [LeverageTradeViewController dismissSocket:Hmodel.selectedModel];
        }
        Hmodel.selectedModel = model;
        Hmodel.isNeedRemoveDataSource = YES;
        [LeverageTradeViewController openSocket:model];
        wself.tabBarController.selectedIndex = 1;
    };
    
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    NSLog(@"%ld",(long)index);
    

    if (index == 1) {

        
    }else{

    }
    
}


@end
